package org.jeecg.modules.openai.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.openai.entity.AiImgCreateRecord;
import org.jeecg.modules.openai.model.WenXinImageModel;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WenXinService {

    private final static String apikey = "GX8YQf5BZQWNTxqASsnqXU55Y6wRZvsN";

    private final static String SecretKey = "FGpAbhpYGeNG4xnK38D1cVDdMpB6r7uc";

    //文心图片单价
    private final Integer imgPrice = 150;

    @Autowired
    private RedisUtil redisUtil;

    private static String getToken() {


//        if(redisUtil.get("baidu:wenxin:token")!=null){
//            return (String) redisUtil.get("baidu:wenxin:token");
//        }

        HashMap<String, Object> prm = new HashMap<>();
        prm.put("grant_type", "client_credentials");
        prm.put("client_id", apikey);
        prm.put("client_secret", SecretKey);
        String url = "https://wenxin.baidu.com/moduleApi/portal/api/oauth/token";

        JSONObject rp = new JSONObject(HttpUtil.createPost(url).contentType("application/x-www-form-urlencoded").form(prm).execute().body());

        if (rp.getInt("code") == 0) {
            String token = rp.getStr("data");
            log.info("文心token:{}", token);
//            redisUtil.set("baidu:wenxin:token",token,60*60*20);
            return token;
        } else {
            log.error("文心服务接口调用错误:{}", rp);
            throw new JeecgBootException("服务接口调用错误");
        }
    }

    @Autowired
    private IAiImgCreateRecordService iAiImgCreateRecordService;
    @Autowired
    private ISysUserService sysUserService;

    public AiImgCreateRecord createImg(WenXinImageModel imageModel) throws UnsupportedEncodingException {


        String url = "https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/txt2img?access_token=" + getToken();
        HashMap<String, Object> prm = new HashMap<>();
        prm.put("text", imageModel.getText());
        prm.put("style", imageModel.getStyle());
        prm.put("num", imageModel.getNum());
        prm.put("resolution",imageModel.getResolution());
        JSONObject rp = new JSONObject(HttpUtil.createRequest(Method.PUT, url).form(prm).execute().body());

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        log.info("结果:{}", rp);
        AiImgCreateRecord record = new AiImgCreateRecord();
        sysUserService.updateUserScore(sysUser.getId(),imgPrice*-1* imageModel.getNum());
        if (rp.getInt("code") == 0) {

            SysUser user = sysUserService.getById(sysUser.getId());
            record.setImgs("");
            record.setIsPush(true);
            record.setPrompt(imageModel.getText());
            record.setUserId(sysUser.getId());
            record.setAvatar(user.getAvatar());
            record.setNickName(user.getNickName());
            record.setNum(imageModel.getNum());
            record.setMsgId(rp.getJSONObject("data").getStr("taskId"));
            iAiImgCreateRecordService.save(record);

        }else{
            log.error("接口调用失败:{}",rp);

            throw new JeecgBootException("接口调用失败:"+rp.getInt("code"));
        }



        return record;
    }

    @Autowired
    private OpenApiService apiService;

    public AiImgCreateRecord wenXinGetImg(String msg){

        String url = "https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/getImg?access_token=" + getToken();
        HashMap<String, Object> prm = new HashMap<>();
        prm.put("taskId", msg);
        AiImgCreateRecord record = iAiImgCreateRecordService.getOne(new QueryWrapper<AiImgCreateRecord>().eq("msg_id",msg));
        if(StringUtils.isNotBlank(record.getImgs())){
            return record;
        }
        JSONObject rp = new JSONObject(HttpUtil.createRequest(Method.PUT, url).form(prm).execute().body());

        log.info("结果:{}", rp);

        if (rp.getInt("code") == 0) {
            JSONObject data = rp.getJSONObject("data");
            if(data.getInt("status")==1){
                List<String> list = new ArrayList<>();
                JSONArray imgs = data.getJSONArray("imgUrls");
                for(int i=0;i<imgs.size();i++){
                    list.add(imgs.getJSONObject(i).getStr("image"));
                }
                record.setImgs(new JSONArray(list).toString());

                iAiImgCreateRecordService.updateById(record);
                //图片本地化;
                apiService.localImgs(record);

                return record;
            }
        }else if(rp.getInt("code")==4002){
            log.info("图片不合规退款");
            sysUserService.updateUserScore(record.getUserId(),record.getNum()*imgPrice);
            iAiImgCreateRecordService.removeById(record.getId());
        }

        return null;
    }


    public static void main(String[] args) throws UnsupportedEncodingException {


    }
}
